<template>
  <transition name="fade">
    <dl ref="menu" class="group-opearMenu" v-if="modelValue" v-outClose="handleToShow">
      <dt v-if="noGroupCount" @click="openNoGroup">添加成员</dt>
      <dt @click="openDialog(1)">修改分组名</dt>
      <dt @click="openDialog(2)">删除分组</dt>
    </dl></transition
  ><confirm-dialog
    to=".chat-box"
    v-model="showDialog"
    width="35%"
    :title="titleText"
    :isLoading="isLoading"
    @confirm="confirm(executeType)"
  >
    <el-input
      v-if="executeType === 1"
      v-model.trim="newGroup"
      ref="groupRef"
      :disabled="isLoading"
      maxlength="16"
      placeholder="输入新的分组名"
      @keypress.enter.prevent="confirm(1)"
      style="width: 70%"
    />
    <p v-else>确定删除该分组？（不会删除该分组下的好友）</p>
  </confirm-dialog>
  <no-group v-model="showNoGroup" :group="group"></no-group>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import vOutClose from "@/directives/vueClickClose";
import { useUserPinia } from "@/pinia/user";
import { storeToRefs } from "pinia";
import { useFriendPinia } from "@/pinia/friend";
import { ElMessage } from "element-plus";
import confirmDialog from "@/components/confirmDialog.vue";
import noGroup from "./noGroup.vue";
import { useRoute, useRouter } from "vue-router";

const props = defineProps<{
  modelValue: boolean;
  group: string;
}>();
const emits = defineEmits<{
  (e: "update:modelValue", show: boolean): void;
}>();

const { user } = storeToRefs(useUserPinia());
const friendStore = useFriendPinia();

const route = useRoute();
const router = useRouter();

/**
 * 无分组人员的个数
 */
const noGroupCount = computed(
  () => friendStore.friendsManage.get("groups")?.groups?.get("无分组")?.count
);

/**
 * 改变该组件的显示状态
 */
const handleToShow: (show: boolean) => void = (show: boolean): void => {
  emits("update:modelValue", show);
};

/**
 * 是否显示确认操作的对话框
 */
const showDialog = ref<boolean>(false);
/**
 * 是否正在删除该好友
 */
const isLoading = ref<boolean>(false);
/**
 * 当前操作执行的类型(1代表像该分组添加成员，2代表修改分组名操作，3代表删除该分组)
 */
const executeType = ref<1 | 2>(1);
/**
 * 执行哪类操作的文本提示
 */
const titleText = ref<string>("");
/**
 * 修改后的新的分组名
 */
const newGroup = ref<string>();
/**
 * 给设置分组输入框一个ref属性
 */
const groupRef = ref<any>();

// 准备打开对话框
const openDialog = (type: 1 | 2) => {
  emits("update:modelValue", false);
  executeType.value = type;
  switch (type) {
    case 1:
      titleText.value = "修改分组名";
      newGroup.value = props.group;
      setTimeout(() => groupRef.value.focus(), 200);
      break;
    case 2:
      titleText.value = "删除分组";
      break;
  }
  showDialog.value = true;
};

// 确认执行
const confirm = (type: 1 | 2) => {
  switch (type) {
    case 1:
      if (!newGroup.value) showDialog.value = false;
      else if (props.group === newGroup.value) showDialog.value = false;
      else if (friendStore.friendsManage.get("groups")?.groups?.has(newGroup.value))
        ElMessage({
          type: "error",
          message: "该分组已存在",
          duration: 1500,
        });
      else if (!isLoading.value) {
        isLoading.value = true;
        friendStore
          .modifyGroupName({
            selfId: user.value.userId,
            oldGroup: props.group,
            newGroup: newGroup.value,
          })
          .then((code: number) => {
            isLoading.value = false;
            if (code === 1) {
              showDialog.value = false;
              ElMessage({
                type: "success",
                message: "修改成功",
                duration: 1500,
              });
              if (route.name === "commManageFriends" && route.query.type === props.group)
                router.replace({
                  name: "commManageFriends",
                  params: { title: "groups" },
                  query: { type: newGroup.value },
                });
            } else {
              ElMessage({
                type: "error",
                message: "修改失败",
                duration: 1500,
              });
              groupRef.value.focus();
            }
          })
          .catch(() => {
            isLoading.value = false;
            groupRef.value.focus();
            ElMessage({
              type: "error",
              message: "修改失败",
              duration: 1500,
            });
          });
      }
      break;
    case 2:
      isLoading.value = true;
      const groupsData = friendStore.friendsManage.get("groups")!.groups!;
      friendStore
        .deleteGroup({
          selfId: user.value.userId,
          group: props.group,
          isNeed:
            !groupsData.get(props.group)?.isRequest &&
            groupsData.get("无分组")?.isRequest,
        })
        .then((code: number) => {
          isLoading.value = false;
          if (code === 1) {
            showDialog.value = false;
            ElMessage({
              type: "success",
              message: "删除成功",
              duration: 1500,
            });
          } else
            ElMessage({
              type: "error",
              message: "删除失败",
              duration: 1500,
            });
        })
        .catch(() => {
          isLoading.value = false;
          ElMessage({
            type: "error",
            message: "删除失败",
            duration: 1500,
          });
        });
      break;
  }
};

/**
 * 是否显示无分组列表组件
 */
const showNoGroup = ref<boolean>(false);

// 打开无分组数据组件
const openNoGroup = () => {
  emits("update:modelValue", false);
  showNoGroup.value = true;
};
</script>

<style lang="scss" scoped>
.fade {
  @include fade(0.15s, ease);
}

.group-opearMenu {
  @include opearMenu(999, 13px);

  dt {
    padding: 5px 20px 5px 15px;
  }
}
</style>
